package com.example.fashionshoes.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayConfig;
import com.alipay.easysdk.factory.Factory;
import com.example.fashionshoes.config.AliPayConfig;
import com.example.fashionshoes.pojo.dto.OrderDTO;
import com.example.fashionshoes.pojo.po.Order;
import com.example.fashionshoes.service.OrderService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/pay")
@Transactional(rollbackFor = Exception.class)
public class PayController {

    @Resource
    AliPayConfig aliPayConfig;
    @Resource
    private OrderService orderService;
    @Resource
    private RabbitTemplate rabbitTemplate;
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "utf-8";
    private static final String SIGN_TYPE = "RSA2";

    @GetMapping("/alipay")
    public void pay(String number, HttpServletResponse httpResponse) throws Exception {
        //初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());
        //获取订单信息
        List<Order> orderList = orderService.lambdaQuery().eq(Order::getNumber, number).list();
        AlipayTradePagePayRequest request = getAlipayTradePagePayRequest(number, orderList);
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    private AlipayConfig getAlipayConfig() {
        AlipayConfig config = new AlipayConfig();
        config.setServerUrl(GATEWAY_URL);
        config.setAppId(aliPayConfig.getAppId());
        config.setPrivateKey(aliPayConfig.getAppPrivateKey());
        config.setFormat(FORMAT);
        config.setAlipayPublicKey(aliPayConfig.getAlipayPublicKey());
        config.setCharset(CHARSET);
        config.setSignType(SIGN_TYPE);
        return config;

    }

    private AlipayTradePagePayRequest getAlipayTradePagePayRequest(String number, List<Order> orderList) {

        BigDecimal totalNumber = new BigDecimal(0);
        BigDecimal discountPrice = orderList.getFirst().getDiscountPrice();
        //本应该是商品名称,而不是固定的
        String subject = "潮鞋";
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        request.setBizContent("{\"out_trade_no\":\"" + number + "\","
                + "\"total_amount\":\"" + discountPrice + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        return request;
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            String tradeNo = params.get("out_trade_no");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                //使用rabbitmq异步处理订单流程
                OrderDTO orderDTO = OrderDTO.builder()
                        .number(tradeNo)
                        .totalNum(params.get("total_amount"))
                        .build();
                Message message = MessageBuilder.withBody(JSONObject.toJSONString(orderDTO).getBytes()).build();
                rabbitTemplate.convertAndSend("exchange.direct","order",message);
            }
        }
        return "success";
    }
}
